package com.znsb.mxk.download;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

public class UpdateAppBroadCastHandler {
	/** app更新交互广播action的头部 为避免广播冲突可在此配置 **/
	private static final String BROAD_CAST_ACTION_HEADER = "com.my.application.update.";
	private Context context;
	private MyBroadCastReceiver receiver;
	private OnReceiveUpdateListener listener;
	private String TAG = getClass().getPackage().getName();

	public UpdateAppBroadCastHandler(Context context, OnReceiveUpdateListener listener) {
		this.context = context;
		this.listener = listener;
	}

	/**
	 * 更新广播接收器
	 *
	 */
	private class MyBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null && listener != null && !TextUtils.isEmpty(intent.getAction())) {
				String action = intent.getAction();
				switch (action) {
				case UpdateAppConstant.NOTIFACTION_UPDATE_BROAD_CASE_ACTION:// 接到通知下载或安装更新
					UpdateAppBean bean = (UpdateAppBean) intent
							.getParcelableExtra(UpdateAppConstant.UPDATE_APP_CONTENT_KEY);
					listener.onReceiveUpdateApp(bean);
					break;
				case UpdateAppConstant.NET_WORK_CHANGED_BROAD_CASE_ACTION:// 接收到网络变化
					listener.onReceiveNetWorkChanged();
					break;
				case UpdateAppConstant.SEND_SERVICE_STATUS_ACTION:// 接收到service里面发送的service下载状态监听
					boolean isDownloading = intent.getBooleanExtra(UpdateAppConstant.KEY_IS_DOWNLOADING, false);
					boolean isExits = intent.getBooleanExtra(UpdateAppConstant.KEY_APP_FILE_EXITES, false);
					boolean isAutorunning = intent.getBooleanExtra(UpdateAppConstant.KEY_SERVICE_IS_AUTO_RUNNING,
							false);
					listener.onReceiveServiceStatus(isDownloading, isExits, isAutorunning);
					break;
				case UpdateAppConstant.CHECK_SERVICE_STATE_ACTION:// 接收到外部请求获取service下载状态广播
					listener.onReceiveRequestServiceStatus();
					break;
				case UpdateAppConstant.ON_DOWNLOAD_PROGRESS_CHANGED:// 接收到更新进度改变广播
					long current = intent.getLongExtra(UpdateAppConstant.KEY_CURRENT_PROGRESS, 0);
					long total = intent.getLongExtra(UpdateAppConstant.KEY_TOTAL_PROGRESS, 0);
					listener.onReviceProgressChanged(current, total);
					break;
				case UpdateAppConstant.CANCEL_UPDATE_SERVICE:// 取消更新
					listener.onReviceCancelUpdate();
					break;
				case UpdateAppConstant.PAUSE_UPDATE_SERVICE:// 暂停更新
					listener.onRevicePauseUpdate();
					break;
				case UpdateAppConstant.RESTART_UPDATE_SERVICE:// 重新开始下载
					listener.onReviceRestartUpdate();
					break;
				default:
					break;
				}
			}
		}
	}

	/**
	 * 接收广播的回调
	 * 
	 * @author Win7
	 *
	 */
	public static interface OnReceiveUpdateListener {
		/** 收到下载或者安装更细 **/
		public void onReceiveUpdateApp(UpdateAppBean updateBean);

		/** 接收到网络状态变化广播 **/
		public void onReceiveNetWorkChanged();

		/** 接收到请求service下载状态监听广播(用于服务里面接收值) **/
		public void onReceiveRequestServiceStatus();

		/** 接收到service里面发送的下载状态监听广播(用于外部监听服务) **/
		public void onReceiveServiceStatus(boolean isDownloading, boolean appFileIsExists, boolean isAutoRunning);

		/** 监听到下载进度改变 **/
		public void onReviceProgressChanged(long current, long total);

		/** 取消更新 **/
		public void onReviceCancelUpdate();

		/** 暂停更新 **/
		public void onRevicePauseUpdate();

		/** 暂停后重新开始更新 **/
		public void onReviceRestartUpdate();
	}

	/**
	 * 常量
	 *
	 */
	public static interface UpdateAppConstant {
		/****************** 广播的action ************************/
		/** 发送更新APP通知广播的action **/
		public static final String NOTIFACTION_UPDATE_BROAD_CASE_ACTION = BROAD_CAST_ACTION_HEADER
				+ "action.notifiction.service.update";
		/** 监听网络变化广播 **/
		public static final String NET_WORK_CHANGED_BROAD_CASE_ACTION = ConnectivityManager.CONNECTIVITY_ACTION;
		/** 发送广播检查service下载状态 **/
		public static final String CHECK_SERVICE_STATE_ACTION = BROAD_CAST_ACTION_HEADER
				+ "action.check.update.app.service.status";
		/** 接收service下载状态的广播action **/
		public static final String SEND_SERVICE_STATUS_ACTION = BROAD_CAST_ACTION_HEADER
				+ "action.send.update.app.service.status";
		/** 发送更新进度广播的action **/
		public static final String ON_DOWNLOAD_PROGRESS_CHANGED = BROAD_CAST_ACTION_HEADER
				+ "action.update.on.download.progress.changed";
		/** 取消更新 **/
		public static final String CANCEL_UPDATE_SERVICE = BROAD_CAST_ACTION_HEADER
				+ "action.update.cancel.update.service";
		/** 暂停更新 **/
		public static final String PAUSE_UPDATE_SERVICE = BROAD_CAST_ACTION_HEADER
				+ "action.update.pause.update.service";
		/** 暂停后继续开始更新 **/
		public static final String RESTART_UPDATE_SERVICE = BROAD_CAST_ACTION_HEADER
				+ "action.restart.pause.update.service";

		/**************** 传值的key **************************/
		/** 更新后传递更细信息key **/
		public static final String UPDATE_APP_CONTENT_KEY = "UPDATE_APP_CONTENT_KEY";
		/** 是否正在下载 **/
		public static final String KEY_IS_DOWNLOADING = "KEY_IS_DOWNLOADING";
		/** app文件是否已经存在 **/
		public static final String KEY_APP_FILE_EXITES = "KEY_APP_FILE_EXITES";
		/** 下载的当前进度 **/
		public static final String KEY_CURRENT_PROGRESS = "KEY_CURRENT_PROGRESS";
		/** 总进度 **/
		public static final String KEY_TOTAL_PROGRESS = "KEY_TOTAL_PROGRESS";
		/** 下载服务是否是在后台静默运行 **/
		public static final String KEY_SERVICE_IS_AUTO_RUNNING = "KEY_SERVICE_IS_AUTO_RUNNING";
	}

	/**
	 * 调用此方法注册广播
	 * 
	 * @param action
	 */
	public void registerBroadCastReceiver(String action) {
		if (receiver == null) {
			receiver = new MyBroadCastReceiver();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(action);
		context.registerReceiver(receiver, filter);
	}

	/**
	 * 根据action发送广播
	 * 
	 * @param action
	 */
	public void sendBroadCast(String action) {
		Intent intent = new Intent();
		intent.setAction(action);
		context.sendBroadcast(intent);
	}

	public void sendUpdateContentBroadCaset(UpdateAppBean bean) {
		if (bean != null && bean.isSendDownloadProgress()) {
			registerBroadCastReceiver(UpdateAppConstant.ON_DOWNLOAD_PROGRESS_CHANGED);
		}

		Intent intent = new Intent();
		intent.putExtra(UpdateAppConstant.UPDATE_APP_CONTENT_KEY, bean);
		intent.setAction(UpdateAppConstant.NOTIFACTION_UPDATE_BROAD_CASE_ACTION);
		context.sendBroadcast(intent);
	}

	/**
	 * 发送广播请求服务状态 在服务里面接收到广播后会将服务的当前情况以广播的形式返回回来
	 */
	public void sendBroadCastForRequestServiceState() {
		Intent intent = new Intent();
		intent.setAction(UpdateAppConstant.CHECK_SERVICE_STATE_ACTION);
		context.sendBroadcast(intent);
	}

	/**
	 * 发送更新进度广播
	 * 
	 * @param current
	 * @param total
	 */
	public void sendProgressChangedBroadCaset(long current, long total) {
		Intent intent = new Intent();
		intent.putExtra(UpdateAppConstant.KEY_CURRENT_PROGRESS, current);
		intent.putExtra(UpdateAppConstant.KEY_TOTAL_PROGRESS, total);
		intent.setAction(UpdateAppConstant.ON_DOWNLOAD_PROGRESS_CHANGED);
		context.sendBroadcast(intent);
	}

	/**
	 * 发送
	 * 
	 * @param isDownloading
	 *            是否正在下载
	 * @param appFileIsExists
	 *            需要安装的app是否已经存在
	 * @param isAutoRunning
	 *            是否是在后台静默下载更新（当设置了 下载后不自动安装、下载时在通知栏不提示进度、下载时不监听下载进度就认为属于静默下载）
	 */
	public void sendBroadCaseServiceDownloadStatus(boolean isDownloading, boolean appFileIsExists,
			boolean isAutoRunning) {
		Intent intent = new Intent();
		intent.putExtra(UpdateAppConstant.KEY_IS_DOWNLOADING, isDownloading);
		intent.putExtra(UpdateAppConstant.KEY_APP_FILE_EXITES, appFileIsExists);
		intent.putExtra(UpdateAppConstant.KEY_SERVICE_IS_AUTO_RUNNING, isAutoRunning);
		intent.setAction(UpdateAppConstant.SEND_SERVICE_STATUS_ACTION);
		context.sendBroadcast(intent);
	}

	/**
	 * 当activity销毁 或者不需要广播时调用此方法取消广播监听
	 */
	public void unRegisterReceiver() {
		if (receiver != null) {
			context.unregisterReceiver(receiver);
		}
	}

	/**
	 * 判断服务是否开启
	 * 
	 * @param mContext
	 * @return
	 */
	public boolean isServiceWork(Context mContext, Class<?> clasz) {
		String serviceName = clasz.getName();
		Log.i(TAG, serviceName);
		boolean isWork = false;
		ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> myList = myAM.getRunningServices(1024);
		if (myList.size() <= 0) {
			return false;
		}
		for (int i = 0; i < myList.size(); i++) {
			String mName = myList.get(i).service.getClassName().toString();
			if (mName.equals(serviceName)) {
				isWork = true;
				break;
			}
		}
		return isWork;
	}

	/**
	 * 发送暂停广播
	 */
	public void pauseUpdate() {
		sendBroadCast(UpdateAppConstant.PAUSE_UPDATE_SERVICE);
	}

	/**
	 * 发送取消下载广播
	 */
	public void cancelUpdate() {
		sendBroadCast(UpdateAppConstant.CANCEL_UPDATE_SERVICE);
	}

	/**
	 * 暂停后重新下载
	 */
	public void restartUpdate() {
		sendBroadCast(UpdateAppConstant.RESTART_UPDATE_SERVICE);
	}
}
